$(document).ready(function () {
    window.filesList = [];
   let table = $('#PartnerTable').DataTable({
            "fnPreDrawCallback": function (oSettings) {
                var processing_div = $('#PartnerTable_processing');
                processing_div.removeClass("card");
                processing_div.addClass("align-middle");

            },
            "ajax": {
                url: "/api/partner/list/",
                type: "GET",
                dataSrc: "results"
            },
            "ordering": false,
            "serverSide": false,
            "paging": true,
            "lengthChange": false,
            "searching": true,
            "bProcessing": true,
            "dom": "<'row'<'col-sm-12 col-md-12'f>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
            // "dom": 'lrtip',
            "language": {
                "sSearch": "",
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "没有数据！",
                "sEmptyTable": "当前未查询到信息",
                "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
                "sInfoEmpty": "显示0到0条记录",
                "sInfoFiltered": "数据表中共有 _MAX_ 条记录",
                "sProcessing": '<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>\n' +
                    '<span class="sr-only">Loading...</span>',
                "sLoadingRecords": '',
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"

                }
            },
            "columns": [
                {
                    "data": 'partners'
                },
                {
                    "data": {},
                    "render": function (data) {
                        if (data['partners_logo']){
                            return '<img class="img-fluid" style="width: 150px; height: 100px" src="'+ data['partners_logo'] +'" alt="'+data['partners']+'">'
                        } {
                            return ''
                        }
                    }

                },                {
                    "data": 'partners_url',
                    "render": function (partners_url) {
                        return '<a href="' + partners_url +'">' + partners_url + '</a>'
                    }

                },
                {
                    "data": 'create_time'
                },
                {
                    "data": 'description',

                },
                {
                    "data": {},
                    "render": function (data) {
                        return '<a href="javascript:void(0);" style="text-decoration: none" onclick="edit_partner(\''+ data['partners']+ '\',\''+ data['partners_url']+'\', \''+ data['description'] +'\', \''+ data['id'] +'\')">编辑</a>&nbsp;' +
                            '<a href="javascript:void(0);" style="text-decoration: none" onclick="delete_partner(\''+ data['id']+'\')">删除</a>&nbsp;' +
                            '<a href="javascript:void(0)" data-toggle="modal" data-target="#uploadImage" onclick="uploadImageModal(\'' + data['id'] + '\')">上传图片</a>'
                    }
                }
            ],
        });
    table.column(3).visible(false);
    $('.dataTables_filter').attr("hidden", "hidden");
});

function submit_partner() {
    let partners = $('#partner_name').val(),
        url = $('#partner_url').val(),
        description = $('#partner_description').val();
    if (partners && url) {

        $.ajax({
            url: "/api/partner/create/",
            type: "POST",
            data: {
                partners: partners,
                partners_url: url,
                description: description
            },
            success: function () {
                let table = $('#PartnerTable').DataTable();
                $('#AddModal').modal('hide');
                table.ajax.reload();
                $('#partner_name').val('');
                $('#partner_url').val('');
                $('#partner_description').val('');
            },
            error: function (e) {
                if (e.status === 400) {
                    if (e.responseText.match("partners with this 合作伙伴名称 already exists")) {
                        alert("伙伴名称已存在")
                    } else {
                        alert("参数有误")
                    }
                }
            }
        })
    }else {
        alert("伙伴信息不能为空")
    }
}

function edit_partner(partner, url, description, pk) {
    $('#edit_partner_name').val(partner);
    $('#edit_partner_url').val(url);
    $('#edit_partner_description').val(description);
    $('#pk').val(pk);
    $('#EditModal').modal('show');
}

function sure_edit() {
    let partner = $('#edit_partner_name').val(),
        url = $('#edit_partner_url').val(),
        description = $('#edit_partner_description').val(),
        pk = $('#pk').val();

    $.ajax({
        url: "/api/partner/update/" + pk + "/",
        type: "PUT",
        data:{
            partners: partner,
            partners_url: url,
            description: description
        },
        success: function () {
            let table = $('#PartnerTable').DataTable();
            $('#EditModal').modal('hide');
            table.ajax.reload()
        },
        error: function () {
            alert("更新失败")
        }
    })
}

function delete_partner(pk) {
    if (window.confirm("确认是否删除该伙伴")){
        $.ajax({
            url: "/api/partner/delete/" + pk + "/",
            type: "DELETE",
            success: function () {
                let table = $('#PartnerTable').DataTable();
                table.ajax.reload()
            },
            error: function () {
                alert("删除失败")
            }
        })
    }else {
        return false
    }
}

$('#uploadImg').change(function () {
    let files = this.files;
    let length = files.length;
    for (let i = 0; i < length; i++) {
        window.filesList.push(files[i]);
    }
    $('.selected-img').remove();
    let list_length = window.filesList.length;
    // for (let j=0;j<window.filesList.length;j++) {
    let fr = new FileReader();
    let img_id = "id_upload_img" + list_length - 1;
    $("#uploadImgBtn").before("<div class=\"selected-img\">\n" +
        "    <i class=\"iconfont icon-delete\" style=\"z-index: 999;background-color:rgba(255,255,255,.8);position: absolute;right: 3px;top: 3px;\" title=\"删除图片\" onclick=\"delete_img(this)\"></i>\n" +
        "    <img id=\"" + img_id + "\" src=\"\" alt=\"待选图片\" style=\"width: 160px;height: 100px;border-radius: 10px;\" onclick=\"show_big_img(this)\">\n" +
        "</div>");

    fr.readAsDataURL(window.filesList[list_length - 1]);//读取文件
    fr.onload = function () {
        $('#' + img_id).attr("src", this.result)
    }
    // }
});

function delete_img(obj) {
    $(obj).parent().remove();
    let id = $(obj).next().attr('id');
    if (id.startsWith("id_upload_img")) {
        let delete_img_id_index = id.replace(/id_upload_img/g,"");
        window.filesList.splice(Number(delete_img_id_index),1);
        console.log(window.filesList);
    }

}

function show_big_img(obj) {
    imgShow("#outerdiv", "#innerdiv", "#bigimg", obj);
}

function imgShow(outerdiv, innerdiv, bigimg, obj) {
    let src = obj.src;//获取当前点击的pimg元素中的src属性
    $(bigimg).attr("src", src);//设置#bigimg元素的src属性
    let windowW = $(window).width();//获取当前窗口宽度
    let windowH = $(window).height();//获取当前窗口高度
    let realWidth = obj.naturalWidth;//获取图片真实宽度
    let realHeight = obj.naturalHeight;//获取图片真实高度
    let imgWidth, imgHeight;
    let scale = 0.8;//缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放

    if (realHeight > windowH * scale) {//判断图片高度
        imgHeight = windowH * scale;//如大于窗口高度，图片高度进行缩放
        imgWidth = imgHeight / realHeight * realWidth;//等比例缩放宽度
        if (imgWidth > windowW * scale) {//如宽度扔大于窗口宽度
            imgWidth = windowW * scale;//再对宽度进行缩放
        }
    } else if (realWidth > windowW * scale) {//如图片高度合适，判断图片宽度
        imgWidth = windowW * scale;//如大于窗口宽度，图片宽度进行缩放
        imgHeight = imgWidth / realWidth * realHeight;//等比例缩放高度
    } else {//如果图片真实高度和宽度都符合要求，高宽不变
        imgWidth = realWidth;
        imgHeight = realHeight;
    }
    $(bigimg).css("width", imgWidth);//以最终的宽度对图片缩放
    let w = (windowW - imgWidth) / 2;//计算图片与窗口左边距
    let h = (windowH - imgHeight) / 2;//计算图片与窗口上边距
    $(innerdiv).css({"top": h, "left": w});//设置#innerdiv的top和left属性
    $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg

    $(outerdiv).click(function () {//再次点击淡出消失弹出层
        $(this).fadeOut("fast");
    });
}

function uploadImageModal(id) {
    $('#product_id_span').text(id);
}

function upload_imgs() {
    let form_data = new FormData();
    let id = $('#product_id_span').text();
    let list_length = window.filesList.length;
    // if (window.filesList.length > 1 ) {
    //     alert("请单张上传,多次上传会取最新的图片")
    // } else {
        //
        // for (let i = 0; i < window.filesList.length; i++) {
    form_data.append('file', window.filesList[list_length - 1]);
    // }
    form_data.append('id', id);
    $.ajax({
        url: '/api/partner_img/upload/',
        type: 'POST',
        data: form_data,
        processData: false,  // tell jquery not to process the data
        contentType: false, // tell jquery not to set contentType
        success: function (callback) {
            alert("上传成功");
            // $("#uploadImage").modal('hide');
            window.location.reload()
        }
    });
}